package 第四周;

/**
 * @author xhw
 */

public class k个一组翻转链表 {

    static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);

        int k = 2;
        ListNode newHead = reverseKGroup(head, k);


        while (newHead != null) {
            System.out.print(newHead.val + " ");
            newHead = newHead.next;
        }
    }

    public static ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode prev = dummy;
        int len = 0;

        ListNode curr = head;
        while (curr != null) {
            len++;
            curr = curr.next;
        }

        for (int i = 0; i < len / k; i++) {
            curr = prev.next;
            ListNode next = curr.next;

            for (int j = 1; j < k; j++) {
                curr.next = next.next;
                next.next = prev.next;
                prev.next = next;
                next = curr.next;
            }

            for (int j = 0; j < k; j++) {
                prev = prev.next;
            }
        }

        return dummy.next;
    }
}